<?php
/***********************************************************
 * Document Type: Function
 * Update: 2006/09/13
 * Author: akon
 * Remark: 公用自定函数
 ***********************************************************/

    /*
     * 执行JS脚本
     *
     * @param string $script_str    需要执行的脚本代码
     */
    function doJS($script_str="") {
        global $charset;
        @header("Content-type: text/html; charset={$charset}");
        echo "<script language=\"javascript\" type=\"text/javascript\">\n";
       // echo "alert('{$script_str}')";
        echo "{$script_str}\n";
        echo "</script>\n";       
    }

    /*
     * 弹出信息窗口
     *
     * @param string $string    提示信息
     */
    function alert($string="") {
        global $charset;
        @header("Content-type: text/html; charset={$charset}");
        echo "<script language=\"javascript\" type=\"text/javascript\">\n";
        echo "alert(\"{$string}\")\n";
        echo "</script>\n";        
    }

    /*
     * 跳转到指定的页面
     *
     * @param string $url       需要转到的URL地址
     * @param string $target    目标窗体
     */
    function goto($url,$target="self") {
        global $charset;
        @header("Content-type: text/html; charset={$charset}");
        echo" <script language=\"javascript\" type=\"text/javascript\">";
        echo $url=="back" ? "history.back(-1)" : "{$target}.location='{$url}'";
        echo "</script>";
        exit;
    }

    /**
     * 过滤特殊字符,用于过滤SQL语句
     *
     * @param string $string
     * @return string 返回一个安全的SQL字符串
     */
    function filter_str($string) {
        return str_replace(array('%', "'", '`', '*', '@', '\\', '&'), array('', '', '', '', '', '', ''), dhtmlspecialchars($string));
    }

    /**
     * 可用于判断HTML页面 CheckBox 的选中状态
     *
     * @param string $val1 值1
     * @param string $val2 值2
     */
    function checked($val1,$val2) {
        if ($val1==$val2) echo 'checked="checked"';
    }

    /**
     * 可用于判断HTML页面 Selected 的选中状态
     *
     * @param string $val1 值1
     * @param string $val2 值2
     */
    function selected($val1,$val2) {
        if ($val1==$val2) echo 'selected="selected"';
    }

    /**
     * 按指定字符切割字符串(支持UTF-8)
     *
     * @param string $string    需要切割的原始字符
     * @param integer $length   切割的字符数量
     * @param string $dot       字符超出时的补充字符
     * @return string 返回一个切割后的字符串
     */
    function cutstr($string, $length, $dot = ' ...') {
        global $charset;
        if(strlen($string) <= $length) return $string;
        $strcut = '';
        if(strtolower($charset) == 'utf-8') {
            $n = $tn = $noc = 0;
            while ($n < strlen($string)) {
                $t = ord($string[$n]);
                if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
                    $tn = 1; $n++; $noc++;
                } elseif(194 <= $t && $t <= 223) {
                    $tn = 2; $n += 2; $noc += 2;
                } elseif(224 <= $t && $t < 239) {
                    $tn = 3; $n += 3; $noc += 2;
                } elseif(240 <= $t && $t <= 247) {
                    $tn = 4; $n += 4; $noc += 2;
                } elseif(248 <= $t && $t <= 251) {
                    $tn = 5; $n += 5; $noc += 2;
                } elseif($t == 252 || $t == 253) {
                    $tn = 6; $n += 6; $noc += 2;
                } else {
                    $n++;
                }
                if ($noc >= $length) break;
             }
            if ($noc > $length) $n -= $tn;
            $strcut = substr($string, 0, $n);
        }
        else {
            for($i = 0; $i < $length - 3; $i++) $strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
        }
        return $strcut.$dot;
    }

    /**
     * 反转换 htmlentities 转换的字符
     *
     * @param string $string    需要转换的字符串
     * @return string
     */
    function unhtmlentities ($string) {
       $trans_tbl1 = get_html_translation_table (HTML_ENTITIES);
       foreach ( $trans_tbl1 as $ascii => $htmlentitie ) $trans_tbl2[$ascii] = '&#'.ord($ascii).';';
       $trans_tbl1 = array_flip ($trans_tbl1);
       $trans_tbl2 = array_flip ($trans_tbl2);
       return strtr (strtr ($string, $trans_tbl1), $trans_tbl2);
    }

    /**
     * 转换所有字符为HTML格式
     *
     * @param string $string    需要格式化的字符串或字符数组
     * @return string
     */
    function dhtmlspecialchars($string) {
        if(is_array($string)) {
            foreach($string as $key => $val)  $string[$key] = dhtmlspecialchars($val);
        }
        else {
            $string = preg_replace('/&amp;((#(\d{3,5}|x[a-fA-F0-9]{4})|[a-zA-Z][a-z0-9]{2,5});)/', '&\\1',
            str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $string));
        }
        return $string;
    }

    /**
     * 加亮关键字
     *
     * @param string $string    需要加亮的字符串
     * @param string $keyword   关键字
     * @return string   返回一个加亮后的字符串
     */
    function light_keyword($string,$keyword) {
        return str_replace($keyword,"<span class=\"highlight_keyword\">$keyword</span>",$string);
    }

    /**
     * 是否合法的邮件格式
     *
     * @param string $email 需要检测的字符串
     * @return mixed    非法格式返回FALSE,否则返回原始字符串
     */
    function is_email($email) {
        return strlen($email) > 6 && preg_match("/^[-_+.[:alnum:]]+@((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+([a-z]{2,4})|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i", $email);
    }

    /**
     * 是否有效的日期格式
     *
     * @param string $ymd   需要检测的字符串
     * @param string $sep   年月日之间的分隔字符
     * @return mixed    非法格式返回FALSE,否则返回原始字符串
     */
    function is_date($ymd, $sep='-') {
        if(!empty($ymd)) {
            list($year, $month, $day) = explode($sep, $ymd);
            return checkdate($month, $day, $year);
        } else return false;
    }

    /**
     * 是否有效的URL地址
     *
     * @param string $url   需要检测的字符串
     * @return mixed    非法格式返回FALSE,否则返回原始字符串
     */
    function is_url($url) {
         return preg_match("/^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"])*$/", $url);
     }

    /**
     * 是否有效的身份证号码(15-18位)
     *
     * @param string $string    需要检测的字符串
     * @return mixed    非法格式返回FALSE,否则返回原始字符串
     */
    function is_idcard($string) {
         return preg_match("/^\d{15}(\d{2}[A-Za-z0-9])?$/", $string);
     }

    /**
     * 检测字符串是否只包含英文(A-Za-z0-9)
     *
     * @param string $string    需要检测的字符串
     * @return mixed    非法格式返回FALSE,否则返回原始字符串
     */
    function is_english($string) {
        return preg_match("/^[A-Za-z0-9]+$/", $string);
        //return true;
     }

    /**
     * 获取客户端IP地址
     *
     * @return string   返回一个IP地址
     */
    function GetIP() {
        if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
            $ip = getenv("HTTP_CLIENT_IP");
        else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
            $ip = getenv("HTTP_X_FORWARDED_FOR");
        else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
            $ip = getenv("REMOTE_ADDR");
        else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
            $ip = $_SERVER['REMOTE_ADDR'];
        else
            $ip = "unknown";
       return($ip);
    }

     /**
     * 获取当前页面的URL地址
     *
     * @return string   返回当前页面的URL地址,包括所有URL参数
     */
    function get_curr_url() {
        $port = $_SERVER["SERVER_PORT"]=="80" ? "" : ":".$_SERVER["SERVER_PORT"];
        $querystr = empty($_SERVER['QUERY_STRING']) ? "" : "?".$_SERVER["QUERY_STRING"];
        return "http://".$_SERVER["SERVER_ADDR"].$port.$_SERVER['PHP_SELF'].$querystr;
    }

    /**
     * 按指定长度生成随机字符串
     *
     * @param interger $length  字符串长度
     * @param boolean $onlynum  是否(True/False)仅限数字
     * @param boolean $upper    是否(True/False)将字符转换为大写
     * @return string 返回指定长度生成随机字符串
     */
    function getRndCode($length=4, $onlynum=true, $upper=false) {
        $codestr = "0123456789";
        $codestr .= $onlynum ? "" : "abcdefghijklmnopqrstuvwxyz";
        for($i=0; $i=999; $i++){
            $order=mt_rand(0,strlen($codestr));
            $codechars .= $codestr[$order];
            if (strlen($codechars)>=$length) break;
        }
        return $upper ? strtoupper($codechars) : $codechars;
    }

    /**
     * 获取指定路径文件的相关信息
     *
     * @param string $filepath  文件名及路径
     * @return array    返回一个包含该文件(路径、文件名、扩展名)小写数组字符
     */
    function get_file_info($filepath) {
        $filename = strtolower(basename($filepath));
        $fileinfo["name"] = $filename;
        $fileinfo["ext"]  = trim(substr(strrchr($filename, '.'), 1));
        $fileinfo["main"] = substr($filename, 0, strlen($filename) - strlen($fileinfo["ext"]) - 1);
        $fileinfo["path"] = str_replace($filename,"",$filepath);
        return $fileinfo;
    }

    /**
     * 获取指定的文件的扩展名
     *
     * @param string $filename  文件名
     * @return string   返回一个小写的文件扩展名
     */
    function get_file_ext($filename) {
        return strtolower(trim(substr(strrchr($filename, '.'), 1)));
    }

    /**
     * 下载一个指定的文件
     *
     * @param string $filepath  文件名及路径
     * @return mixed    如果文件不存在则返回false
     */
    function down_file($filepath) {
        if (!file_exists($filepath)) return false;
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Component: must-revalidate, post-check=0, pre-check=0");
        header("Content-Length: " . filesize($filepath));
        header("Content-Disposition: attachment; filename=\"" . basename($filepath) . "\"");
        header('Content-Transfer-Encoding: binary');
        readfile("$filepath");
        exit;
    }

    /**
     * 检测是否被允许的上传文件格式
     *
     * @param string $ext_name  文件扩展名
     * @return boolean  合法(True)/非法(False)
     */
    function IsValidFile($ext_name) {
        global $allowfiletype;
        return in_array(strtolower($ext_name), explode('|',$allowfiletype));
    }

    /**
     * 是否图片格式文件
     *
     * @param string $ext_name  文件扩展名
     * @return boolean  返回TRUE或FALSE
     */
    function IsImgFile($ext_name) {
        return in_array(strtolower($ext_name), array('gif', 'jpg', 'jpeg', 'bmp', 'png'));
    }

    /**
     * 获取上一级路径
     *
     * @param string $folderPath    原始路径
     * @return string   返回原始路径的上一级路径
     */
    function GetParentFolder( $folderPath ) {
        $sPattern = "-[/\\\\][^/\\\\]+[/\\\\]?$-" ;
        return preg_replace( $sPattern, '', $folderPath ) ;
    }

    /**
     * 获取网站根路径
     *
     * @return string
     */
    function GetRootPath() {
        $sRealPath = realpath( './' ) ;
        $sSelfPath = $_SERVER['PHP_SELF'] ;
        $sSelfPath = substr( $sSelfPath, 0, strrpos( $sSelfPath, '/' ) ) ;
        return substr( $sRealPath, 0, strlen( $sRealPath ) - strlen( $sSelfPath ) ) ;
    }

    /**
     * 转换指定资源中的路径为正确的路径
     *
     * @param string $original_resource  需要转换的内容
     * @return string
     */
    function correct_path($original_resource) {
        global $is_test_space, $test_space_name;
        if ($is_test_space) {
            $file_true_path = __UPLOAD_PATH;
            $file_true_path = str_replace(__SITE_ROOT, "/", $file_true_path);
            $original_resource = str_replace($file_true_path, "/" . $test_space_name . $file_true_path, $original_resource);
            return str_replace("/" . $test_space_name . "/" . $test_space_name . $file_true_path, "/" . $test_space_name . $file_true_path, $original_resource);
        }
        else {
            $file_true_path = __UPLOAD_PATH;
            $file_true_path = str_replace(__SITE_ROOT, "", $file_true_path);
			return str_replace("" . $test_space_name . "/" . $file_true_path, $file_true_path, $original_resource);
        }
    }

    /**
     * 生成图片缩略图
     *
     * @param string $imgfile   文件路径及文件名
     * @param integer $maxW     图片最大宽度
     * @param integer $maxH     图片最大高度
     * @param boolean $remake   是否重新生成缩略图
     * @return array    [message]相关信息/[thumb] 缩略图文件路径及地址
     */
    function mkThumb($imgfile,$maxW=400,$maxH=300,$remake=false) {
        global $is_test_space, $test_space_name;
        $imgfile = './' . $imgfile;
        $imgfile = str_replace("//","/", $imgfile);
        if ($is_test_space && strlen($test_space_name)>2) {
			$imgfile = str_replace("./$test_space_name","../", $imgfile);
		} else {
			$path = substr(__UPLOAD_PATH, strlen(__SITE_ROOT));
			$imgfile = str_replace('./' . $path, '../' . $path, $imgfile);
		}
        $thumb_file = $imgfile;
		
		if (!file_exists($imgfile)) {
            $info["message"] = 2; // 源文件不存在
            return $info;
        }
		
        include_once ( __CLASS_PATH . 'gd_image.class.php');
        $GDImage = new GDImage;
        $img_info = get_file_info($imgfile);
        $thumb_file = $img_info["path"].$maxW."x".$maxH.".".$img_info["main"].".".$img_info["ext"];
        $load = $GDImage->loadFile($imgfile);
        if($load){
            if (!file_exists($thumb_file) || $remake==true) {
                $GDImage->mkThumb($maxW, $maxH);
                $GDImage->build($thumb_file);
                $info["message"] = 0; // 生成缩略图成功
            }
            else $info["message"] = 1; // 文件已经存在或不允许被重写
        }
        else $info["message"] = 3; // 载入源文件失败
        $info["thumb"] = $thumb_file;
        return $info;
    }

    /**
     * 获取图片缩略图
     *
     * @param string $imgfile   文件路径及文件名
     * @param integer $maxW     图片最大宽度
     * @param integer $maxH     图片最大高度
     * @return string    缩略图文件路径及地址
     */
    function getThumb($imgfile,$maxW=400,$maxH=300) {
        $img = mkThumb($imgfile,$maxW,$maxH);
        return ($img["message"]==0 || $img["message"]==1) ? $img["thumb"] : $imgfile;
    }

    /**
     * 获取相反的排序方向
     *
     * @param string $oexp          当前排序方向
     * @param string $default_exp   默认排序方向
     * @return string   返回一个相反的排序方向
     */
    function get_sort_exp($oexp,$default_exp="desc") {
        switch (strtolower($oexp)) {
            case "asc": $oexp = "asc"; break;
            case "desc": $oexp = "desc"; break;
            default: $oexp = $default_exp; break;
        }
        return ($oexp=="desc") ? "asc" : "desc";
    }

    /**
     * 取出单条文章数据
     * @param string $param          替换内容参数
     * @param string $article_id          文章ID
     * @return string   
     */
     function get_artical_content($article_id=0,$param='company'){
         global $plist,$tablepre;
        $plist->RowName = $param;  //$company[0].article_content
        $plist->Execute("select * from `{$tablepre}article` where `article_id`={$article_id}");
        $plist->TplParse();
     }

    /**
     * 创建插入数据的SQL语句
     *
     * @param string $table_name    数据库表名
     * @param array $fields_arr     字段/值数组，例如: $fields_arr = array("Username" => "$Username");
     * @return string   返回一条可执行的SQL语句
     */
    function create_insert_sql($table_name, $fields_arr) {
        foreach ($fields_arr as $k=>$v) {
            if (!empty($keys) && !empty($vals)) {
                $keys .= ", "; $vals .= ", ";
            }
            $keys .= "`{$k}`"; $vals .= "'{$v}'";
        }
        return "insert into `{$table_name}` ({$keys}) values ({$vals})";
    }

    /**
     * 创建修改数据的SQL语句
     *
     * @param string $table_name    数据库表名
     * @param array $fields_arr     字段/值数组，例如: $fields_arr = array("Username" => "$Username");
     * @param string $condition     SQL语句条件，例如: WHERE `id`='$id'
     * @return string   返回一条可执行的SQL语句
     */
    function create_update_sql($table_name, $fields_arr, $condition) {
        foreach ($fields_arr as $k=>$v) {
            if (!empty($sql_str)) $sql_str .= ", ";
            $sql_str .= "`{$k}`='{$v}'";
        }
        return "UPDATE `{$table_name}` SET {$sql_str} {$condition}";
    }

    /**
     * 创建SQL搜索子句
     * $search_arr   : SQL搜索数组
     * $par_junk     : and , 将返回 and (...) 形式子句
     *                 or , 将返回 or (...) 形式子句
     *                 空 , 将返回 ... 子句
     * 例 :
     * $search_arr[] = array( "field" => "title", "keyword" => "aa", "condition" => "like", "junk" => "and" );
     * $search_arr[] = array( "field" => "title", "keyword" => "bb", "condition" => "=", "junk" => "or" );
     * $search_arr[] = array( "field" => "title", "keyword" => "cc", "condition" => ">", "junk" => "and" );
     * create_search_sql($search_arr,"and")
     * 将返回 ： and (`title` like '%aa%' or `title`='bb' and `title`>'cc')
     * 注 ：
     * 数组各字段不能为空
     * field         字段名
     * keyword       搜索关键字
     * condition     查询条件            like , = , > , < , <>
     * junk          条件查询关系        and , or
     */
    function create_search_sql($search_arr,$par_junk="") {
        $first = true;
        foreach ($search_arr as $key=>$val) {
            if (is_array($val)) {
                $junk = ($val["junk"]!="and" && $val["junk"]!="or") ? "" : $val["junk"];
                $field = $val["field"];
                $condition = $val["condition"];
                $keyword = $val["keyword"];
                if (!empty($field) && !empty($condition) && !empty($keyword)) {
                    if ($first) {
                        $junk = "";
                        $first = false;
                    }
                    else $junk = " {$junk}";
                    switch ($condition) { // like , < , > , = , <> ,
                        case "like": $sql_clause .= "{$junk} `{$field}` like '%{$keyword}%'"; break;
                        case "<":
                        case ">":
                        case "=":
                        case "<>": $sql_clause .= "{$junk} `{$field}`{$condition}'{$keyword}'"; break;
                    }
                }
            }
        }
        if (!empty($sql_clause) && ($par_junk=="and" || $par_junk=="or")) $sql_clause = " {$par_junk} ({$sql_clause})";
        return $sql_clause;
    }

    /**
     * 显示XHTML文档Header
     *
     * @param string $header_content    需要插入在Header中的内容
     */
    function show_xhtml_header($header_content="") {
        global $charset;
        echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="'.$charset.'" lang="'.$charset.'">
<head>
<meta http-equiv="Content-Type" content="text/html; charset='.$charset.'" />
<meta http-equiv="Content-Language" content="'.$charset.'" />'."\n";
        if (!empty($header_content)) echo $header_content."\n";
        echo "</head>\n\n<body>\n";
    }

    /**
     * 显示XHTML文档Footer
     *
     * @param string $foot_content  需要插入在Footer中的内容
     */
    function show_xhtml_footer($foot_content="") {
        if (!empty($foot_content)) echo "\n".$foot_content;
        echo "\n</body>\n</html>";
    }

    /**
     * 信息反馈
     *
     * @param string $content   提示信息内容
     * @param string $url       返回链接地址
     * @param string $url_tip   返回链接提示文字
     */
    function feedback($content, $url="javascript:history.go(-1);", $url_tip='') {
        global $tpl, $clang;
        if (empty($url_tip)) $url_tip = $clang['goto_back'];
		if (empty($url)) $url = "javascript:history.go(-1);";
        $tpl->assign("content",$content);
        $tpl->assign("url",$url);
        $tpl->assign("url_tip",$url_tip);
        $tpl->display("feedback.htm");
        exit;
    }

    /**
     * AJAX 处理响应
     *
     * @param string $status_code   响应代码
     * @param string $msg 响应消息
     */
    function ajax_response($status_code, $msg="") {
        global $charset;
        header("Content-type:application/xml");
        echo "<?xml version=\"1.0\" encoding=\"{$charset}\"?>\r\n";
        echo "<response>";
        echo "<status>{$status_code}</status>";
        if (!empty($msg)) echo "<message>{$msg}</message>";
        echo "</response>";
        die();
    }

    /**
     * 查询用户是否已经存在
     *
     * @param string $admin_user  用户名
     * @return boolean  存在则返回TRUE，否则返回FALSE
     */
    function admin_exist($admin_user) {
        global $tablepre, $db;
        if (!empty($admin_user)) {
            $query = $db->query("select `admin_user` from `{$tablepre}admin_user` where `admin_user`='{$admin_user}'");
            return $db->num_rows($query) ? true : false;
        }
    }

    /**
     * 查询组是否已经存在
     *
     * @param string $group_name 组名称
     * @return boolean  存在则返回TRUE，否则返回FALSE
     */
    function group_exist($group_name) {
        global $tablepre, $db;
        if (!empty($group_name)) {
            $query = $db->query("select `group_name` from `{$tablepre}admin_group` where `group_name`='{$group_name}'");
            return $db->num_rows($query) ? true : false;
        }
    }

/* 功能：PHP图片水印 (水印支持图片或文字)
* 参数：
*      $groundImage    背景图片，即需要加水印的图片，暂只支持GIF,JPG,PNG格式；
*      $waterPos        水印位置，有10种状态，0为随机位置；
*                        1为顶端居左，2为顶端居中，3为顶端居右；
*                        4为中部居左，5为中部居中，6为中部居右；
*                        7为底端居左，8为底端居中，9为底端居右；
*      $waterImage        图片水印，即作为水印的图片，暂只支持GIF,JPG,PNG格式；
*      $waterText        文字水印，即把文字作为为水印，支持ASCII码，不支持中文；
*      $textFont        文字大小，值为1、2、3、4或5，默认为5；
*      $textColor        文字颜色，值为十六进制颜色值，默认为#FF0000(红色)；
*
* 注意：Support GD 2.0，Support FreeType、GIF Read、GIF Create、JPG 、PNG
*      $waterImage 和 $waterText 最好不要同时使用，选其中之一即可，优先使用 $waterImage。
*      当$waterImage有效时，参数$waterString、$stringFont、$stringColor均不生效。
*      加水印后的图片的文件名和 $groundImage 一样。
* 作者：longware @ 2004-11-3 14:15:13
*/
function imageWaterMark ( $groundImage , $waterPos = 0 , $waterImage = "" , $waterText = "" , $textFont = 5 , $textColor = "#FF0000" ){
     $isWaterImage = FALSE ;
     $formatMsg = "暂不支持该文件格式，请用图片处理软件将图片转换为GIF、JPG、PNG格式。" ;

     //读取水印文件
     if(!empty( $waterImage ) && file_exists ( $waterImage ))
    {
         $isWaterImage = TRUE ;
         $water_info = getimagesize ( $waterImage );
         $water_w     = $water_info [ 0 ]; //取得水印图片的宽
         $water_h     = $water_info [ 1 ]; //取得水印图片的高

         switch( $water_info [ 2 ]) //取得水印图片的格式
         {
            case 1 : $water_im = imagecreatefromgif ( $waterImage );break;
            case 2 : $water_im = imagecreatefromjpeg ( $waterImage );break;
            case 3 : $water_im = imagecreatefrompng ( $waterImage );break;
            default:die( $formatMsg );
        }
    }

     //读取背景图片
     if(!empty( $groundImage ) && file_exists ( $groundImage ))
    {
         $ground_info = getimagesize ( $groundImage );
         $ground_w     = $ground_info [ 0 ]; //取得背景图片的宽
         $ground_h     = $ground_info [ 1 ]; //取得背景图片的高

         switch( $ground_info [ 2 ]) //取得背景图片的格式
         {
            case 1 : $ground_im = imagecreatefromgif ( $groundImage );break;
            case 2 : $ground_im = imagecreatefromjpeg ( $groundImage );break;
            case 3 : $ground_im = imagecreatefrompng ( $groundImage );break;
            default:die( $formatMsg );
        }
    }
    else
    {
        die( "需要加水印的图片不存在！" );
    }

     //水印位置
     if( $isWaterImage ) //图片水印
     {
         $w = $water_w ;
         $h = $water_h ;
         $label = "图片的" ;
    }
    else //文字水印
     {
         $temp = imagettfbbox ( ceil ( $textFont * 2.5 ), 0 , "./fonts/arialbd.ttf" , $waterText ); //取得使用 TrueType 字体的文本的范围
         $w = $temp [ 2 ] - $temp [ 6 ];
         $h = $temp [ 3 ] - $temp [ 7 ];
        unset( $temp );
         $label = "文字区域" ;
    }
    if( ( $ground_w < $w ) || ( $ground_h < $h ) )
    {
        echo "需要加水印的图片的长度或宽度比水印" . $label . "还小，无法生成水印！" ;
        return;
    }
    switch( $waterPos )
    {
        case 0 : //随机
             $posX = rand ( 0 ,( $ground_w - $w ));
             $posY = rand ( 0 ,( $ground_h - $h ));
            break;
        case 1 : //1为顶端居左
             $posX = 0 ;
             $posY = 0 ;
            break;
        case 2 : //2为顶端居中
             $posX = ( $ground_w - $w ) / 2 ;
             $posY = 0 ;
            break;
        case 3 : //3为顶端居右
             $posX = $ground_w - $w ;
             $posY = 0 ;
            break;
        case 4 : //4为中部居左
             $posX = 0 ;
             $posY = ( $ground_h - $h ) / 2 ;
            break;
        case 5 : //5为中部居中
             $posX = ( $ground_w - $w ) / 2 ;
             $posY = ( $ground_h - $h ) / 2 ;
            break;
        case 6 : //6为中部居右
             $posX = $ground_w - $w ;
             $posY = ( $ground_h - $h ) / 2 ;
            break;
        case 7 : //7为底端居左
             $posX = 0 ;
             $posY = $ground_h - $h ;
            break;
        case 8 : //8为底端居中
             $posX = ( $ground_w - $w ) / 2 ;
             $posY = $ground_h - $h ;
            break;
        case 9 : //9为底端居右
             $posX = $ground_w - $w ;
             $posY = $ground_h - $h ;
            break;
        default: //随机
             $posX = rand ( 0 ,( $ground_w - $w ));
             $posY = rand ( 0 ,( $ground_h - $h ));
            break;
    }

     //设定图像的混色模式
     imagealphablending ( $ground_im , true );

    if( $isWaterImage ) //图片水印
     {
         imagecopy ( $ground_im , $water_im , $posX , $posY , 0 , 0 , $water_w , $water_h ); //拷贝水印到目标文件
     }
    else //文字水印
     {
        if( !empty( $textColor ) && ( strlen ( $textColor )== 7 ) )
        {
             $R = hexdec ( substr ( $textColor , 1 , 2 ));
             $G = hexdec ( substr ( $textColor , 3 , 2 ));
             $B = hexdec ( substr ( $textColor , 5 ));
        }
        else
        {
            die( "水印文字颜色格式不正确！" );
        }
         imagestring ( $ground_im , $textFont , $posX , $posY , $waterText , imagecolorallocate ( $ground_im , $R , $G , $B ));
    }

     //生成水印后的图片
     @ unlink ( $groundImage );
    switch( $ground_info [ 2 ]) //取得背景图片的格式
     {
        case 1 : imagegif ( $ground_im , $groundImage );break;
        case 2 : imagejpeg ( $ground_im , $groundImage );break;
        case 3 : imagepng ( $ground_im , $groundImage );break;
        default:die( $errorMsg );
    }

     //释放内存
     if(isset( $water_info )) unset( $water_info );
    if(isset( $water_im )) imagedestroy ( $water_im );
    unset( $ground_info );
     imagedestroy ( $ground_im );
}

    //获取参数值
    function GetPostValue($str){
       global $website_rewrite,$GetRewriteValue;
       if($website_rewrite){
          $re_val = $GetRewriteValue[$str];
       }
       else{
            $re_val = postget($str);
       }
       return $re_val;
    }

	//模板中的动态链接 转换为 伪静态链接W
	function url_Make($str,$State = false,$DefaultFileName = 'index',$varOpen = true,$varORvar = '/',$varORvalue = '-',$suffix = '.do')
	{
        global $website_rewrite;
		@extract($str,$State,$DefaultFileName,$varOpen,$varORvar,$varORvalue);
		//$State			= (empty($str['State'])) ? true : $str['State'];
        $State			= $website_rewrite==true ? true : false;
		$DefaultFileName	= (empty($str['DefaultFileName'])) ? 'index' : $str['DefaultFileName'];
		$varOpen		= (empty($str['varOpen'])) ? true : $str['varOpen'];
		$varORvar		= (empty($str['varORvar'])) ? ',' : $str['varORvar'];
		$varORvalue		= (empty($str['varORvalue'])) ? '-' : $str['varORvalue'];
		$str			= $str['str'];

		//关闭直接返回
		if (!$State)
			return $str;

		if (@strrpos($str,'/') === false)
		{
			//总参数
			$cs = explode('?',$str);
		}else{
			ereg("(.*[/{0,}])(.*)",$str,$ArrStr);
			//总参数
			$cs = explode('?',$ArrStr[2]);
		}

		//取得锚
		if (strpos($cs[1],'#') !== false)
		{
			$fragment = (strstr($cs[1],'#'));
			$DTCS = substr($cs[1],0,strpos($cs[1],'#'));
		}else{
			$DTCS = $cs[1];
		}

		$str = '';
		//动态参数
		  parse_str($DTCS,$CSARR);
		  //打开文件名称
		  $CSARR['open'] = (empty($cs[0])) ? $DefaultFileName : substr($cs[0],0,strrpos($cs[0],'.'));

		  if ($varOpen)
		  {
			  foreach ($CSARR as $k => $v)
				  $str .= $varORvar.$k.$varORvalue.$v;
		  }else{
			  foreach ($CSARR as $v)
				  $str .= $varORvar.$v;
		  }
		$str = $ArrStr[1].substr($str,1).$suffix.$fragment;
		echo $str;

	}

    //PHPMaile邮件发送
 function sendEmail($emailSubject,$emailBody,$sendPort,$sendHost,$emailName,$emailPwd,$emailSendFrom,$toEmail,$setssl=false){        
        if(!file_exists(__CLASS_PATH.'class.phpmailer.php')){
            return false;
        }
        include (__CLASS_PATH.'class.phpmailer.php');
        try {
                  $mail = new PHPMailer(true); //New instance, with exceptions enabled

                  $body=$emailBody;
                  //echo $body; exit;
                  //$body             = file_get_contents('contents.html');
                  $body             = preg_replace('/\\\\/','', $body); //Strip backslashes

                  $mail->IsSMTP();                           // tell the class to use SMTP
                  if($setssl){
                      $mail->SMTPSecure = 'ssl'; // 设置连接服务器前缀 相对于smtp采用了ssl连接
                  }
                  $mail->SMTPAuth   = true;                  // enable SMTP authentication
                  $mail->Port       = $sendPort;                   // set the SMTP server port
                  $mail->Host       = $sendHost;        // SMTP server
                  $mail->Username   = $emailName;     // SMTP server username
                  $mail->Password   = $emailPwd;            // SMTP server password

                  //$mail->IsSendmail();  // tell the class to use Sendmail

                  $mail->AddReplyTo($emailSendFrom);

                  $mail->From       = $emailSendFrom;
                  $mail->FromName   = $emailName;

                  $to = $toEmail;

                  $mail->AddAddress($to);

                  $mail->Subject  = $emailSubject;

                  $mail->WordWrap   = 100; // set word wrap

                  $mail->MsgHTML($body);

                  $mail->IsHTML(true); // send as HTML

                  $mail->Send();

                  //echo 'Message has been sent.';
              } catch (phpmailerException $e) {
                  echo $e->errorMessage();
              }
    }

    //去除换行
    function clear_br($str){
        $_str = str_replace("\n","",$str);
        $_str = str_replace("\t","",$_str);
        $_str = str_replace("\r","",$_str);
        return $_str;
    }
    //随机颜色
    function rand_color(){
        for($a=0;$a<6;$a++){    //采用#FFFFFF方法，
            $d.=dechex(rand(0,15));//累加随机的数据--dechex()将十进制改为十六进制
        }
        return '#'.$d;
    }


    //时间格式化
    function FormatDate($GetDate,$stype){
        switch($stype){
            case 1: return date('Y-m-d',strtotime($GetDate)); break;
            case 2: return date('Y/m/d',strtotime($GetDate)); break;
            default: return date('Y-m-d',strtotime($GetDate)); break;
        }
    }

    //获取访问分类名称
    function GetDefaultClass($classid,$tablename=''){
        global $tablepre, $db;
        $tablename = empty($tablename)?"{$tablepre}admin_menu":"{$tablepre}products_class";
        $result = $db->getInfo($classid, 'id', $tablename);
        return $result["class_name"];
    }

    //获取单文章内容信息数组
    function GetArticalCon($article_id){
        global $tablepre, $db;
        $result = $db->getInfo($article_id, 'article_id', "{$tablepre}article");
        if($result) {return $result;}
    }

     //获取幻灯片信息
    function GetBanner($imgs_classid,$bannername){
        global $tablepre, $db;
        $result = $db->select("select imgs_thumb,imgs_url from `{$tablepre}imgs` where imgs_classid= $imgs_classid and imgs_isvalid=1");
        return $result;
        //if($result) {
        //    foreach($result as $value){
        //        $BannerImgList .= $bannername.".Add(\"".correct_path($result["imgs_thumb"])."\", '', '');\n";
        //    }
       // }
    }

    //获取文章左侧列表信息
	
    function GetLeftNav($page_url,$parent_id,$article_id){
       global $tablepre, $db,$urlW;
       $result = $db->select("select id,class_name,param_value from `{$tablepre}admin_menu` where parent_id = $parent_id and isvalid =1 order by sort_order,id ");
       if($result){
           foreach($result as $value){
               $gopage=$page_url.'?cname='.urlencode($value["class_name"]);
               $gopage = empty($value["param_value"])?$gopage:$gopage."&".$value["param_value"];
               //echo $urlW->State==true?1:0; exit;
			   if($urlW->State) $gopage = $urlW->make($gopage);  // rewrite 链接
               $str .= "<li><a href=\"".$gopage."\">".$value["class_name"]."</a></li>";
           }
           return $str;
       }
    }

    //获取信息内容信息数组
    function GetIdCon($id,$table_name){
        global $db, $tpl, $sitename;
        $result = $db->getInfo($id, 'id', $table_name);
        if($result) {
            foreach ($result as $k=>$v) {
                $tpl->assign($k, $v);               
            }
            $tpl->assign('sitename', $result["news_title"].'-'.$sitename);
            if (!empty($result["tags"])){
                $tpl->assign('sitekeywords', $result["tags"]);
            }
        }
    }

    //显示产品功能列表
    function GetSelectlist($arr_content,$param,$con='',$parentid,$classid,$pageCount){
        global $urlW;
        $_arr = explode('||',$arr_content);    
        foreach($_arr as $value){
            $s_css = $con==$value?" class=\"f_bold f_cur\"":"";
            if($urlW->State) {
                $_content .= "<a href=\"".$urlW->make("product.php?parentid=$parentid&classid=$classid&pageCount=$pageCount&$param=".urlencode($value))."\" class=\"green2\"><span$s_css>$value</span></a>,&nbsp"; // rewrite 链接
            }
            else{
                $_content .= "<a href=\"product.php?parentid=$parentid&classid=$classid&pageCount=$pageCount&$param=".urlencode($value)."\" class=\"green2\"><span$s_css>$value</span></a>,&nbsp";
            }
        }            
        return $_content;
    }

    //显示产品默认类别
    function GetProDefaultClass($classid){
        global $db, $tablepre;
        $table_name   = "{$tablepre}products_class"; //表名
        $result = $db->select("SELECT id,parent_id,class_name FROM `{$table_name}`  WHERE `parent_id`='$classid' order by sort_order asc limit 1");
        if($result){
            $classid = $result[0]["id"];
        }
        return $classid;
    }

    //显示产品类别
    function LeftClassTree($paritentid=0,$pid=0,$subid=0){
        global $db, $tablepre,$urlW;
        $table_name   = "{$tablepre}products_class"; //表名

        $result = $db->select("SELECT id,parent_id,class_name FROM `{$table_name}`  WHERE `parent_id`='{$paritentid}' order by sort_order asc");

        if($result){
            $mainCon="<ul>";
            foreach ($result as $value){
                $_result = $db->select("SELECT id,parent_id,class_name FROM `{$table_name}`  WHERE `parent_id`='{$value["id"]}' order by sort_order asc");
                if($_result){
                    $pCls = $pid==$value["id"] ? 'f_cur':"";
                    if($urlW->State){
                        $mainCon=$mainCon."<li class=\"parentcls\"><a href=\"".$urlW->make("product.php?parentid=".$value["id"])."\"><span class=\"$pCls\">{$value["class_name"]}</span></a></li>";
                    }
                    else{
                        $mainCon=$mainCon."<li class=\"parentcls\"><a href=\"product.php?parentid=".$value["id"]."\"><span class=\"$pCls\">{$value["class_name"]}</span></a></li>";
                    }
                    $mainCon .= "<li><ul>";
                    foreach($_result as $val){
                        $subCls = $subid==$val["id"] ? 'f_cur':"";
                        if($urlW->State){
                            $mainCon .= "<li><a href=\"".$urlW->make("product.php?parentid=".$value["id"]."&classid=".$val["id"])."\"><span class=\"$subCls\">{$val["class_name"]}</span></a></li>";
                        }
                        else{
                            $mainCon .= "<li><a href=\"product.php?parentid=".$value["id"]."&classid=".$val["id"]."\"><span class=\"$subCls\">{$val["class_name"]}</span></a></li>";
                        }
                    }
                   $mainCon .= "</ul></li>";  
                }
            }
            $mainCon .= "</ul>";
            return $mainCon;
        }
    }

    //显示产品父/子类
    function GetParentClass($parentid=0,$classid=0){
        global $db, $tablepre,$urlW;
        $table_name   = "{$tablepre}products_class"; //表名
        $result = $db->select("SELECT id,parent_id,class_name FROM `{$table_name}`  WHERE `parent_id`='{$parentid}' order by sort_order asc");
        if($result){
            if($parentid==0){
                foreach($result as $value){
                    $s_css = $classid==$value["id"]?" class=\"f_bold f_cur\"":"";
                    if($urlW->State){
                        $mainCon .= "<a href=\"".$urlW->make("product.php?parentid=".$value["id"])."\" class=\"green2\"><span$s_css>".$value['class_name'].'</span>,&nbsp;';
                    }
                    else{
                        $mainCon .= "<a href=\"product.php?parentid=".$value["id"]."\" class=\"green2\"><span$s_css>".$value['class_name'].'</span>,&nbsp;';
                    }
                }
            }
            else{
               foreach($result as $value){
                    $s_css = $classid==$value["id"]?" class=\"f_bold f_cur\"":"";
                    if($urlW->State){
                        $mainCon .= "<a href=\"".$urlW->make("product.php?parentid=".$parentid."&classid=".$value["id"])."\" class=\"green2\"><span$s_css>".$value['class_name'].'</span>,&nbsp;';
                    }
                    else{
                        $mainCon .= "<a href=\"product.php?parentid=".$parentid."&classid=".$value["id"]."\" class=\"green2\"><span$s_css>".$value['class_name'].'</span>,&nbsp;';
                    }
                }
            }
            return $mainCon;
        }
    }

   
        /*
        函数名称：CheckEmail($email)
        功能：检查EMAIL的合法性
        定义 $email : 待检查的EMAIL地址
        返回值：true 或者 false
        */
        function CheckEmail($email) {
            if (preg_match("/^([a-zA-Z0-9])+([\w-.])*([a-zA-Z0-9])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/",$email)){
               return true;
            }
            else{
                return false;
            }
        }

        //获取长时间
        function GetDates() {
            return date("Y-m-d H:i:s");
        }

        /*
        函数名称：RndPass($num)
        功能：生成$num位随机数
        返回值：随机字符
        */
        function RndPass($num) {
            $return_string = '';
            $tmpstr = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
            for($i=0;$i < $num;$i++){
                $return_string .= $tmpstr{mt_rand(0,strlen($tmpstr)-1)};
            }
            return $return_string;
        }

        /*
        函数名称：AlertMsg($msg,$url)
        功能：提示信息并导向
        返回值：关闭/返回/跳转到$url
        */
        function AlertMsg($msg,$url) {
			//header("Content-Type:text/html;charset=gb2312");
            if (is_int($url)==true)
            {
                if ($url==0)
                {
                    echo "<script>alert(\"$msg\");window.close();</script>";
                }
                else
                {
                    echo "<script>alert(\"$msg\");history.go(-$url);</script>";
                }
            }
            else
            {
                echo "<script>alert(\"$msg\");window.location=\"$url\";</script>";
            }
            exit;
        }


        function random($length, $numeric = 0) {
            PHP_VERSION < '4.2.0' ? mt_srand((double)microtime() * 1000000) : mt_srand();
            $seed = base_convert(md5(print_r($_SERVER, 1).microtime()), 16, $numeric ? 10 : 35);
            $seed = $numeric ? (str_replace('0', '', $seed).'012340567890') : ($seed.'zZ'.strtoupper($seed));
            $hash = '';
            $max = strlen($seed) - 1;
            for($i = 0; $i < $length; $i++) {
                $hash .= $seed[mt_rand(0, $max)];
            }
            return $hash;
        }

        function stripsearchkey($string) {
            if(is_array($string)) {
                foreach($string as $key => $val) {
                    $string[$key] = stripsearchkey($val);
                }
            } else {
                $string = trim($string);
                $string = str_replace('*', '%', addcslashes($string, '%_'));
                $string = str_replace('_', '\_', $string);
            }
            return $string;
        }

        function postget($var) {
            $value = '';
            if(isset($_POST[$var])) {
                $value = $_POST[$var];
            } elseif (isset($_GET[$var])) {
                $value = $_GET[$var];
            }
            return $value;
        }

        function authcode($string, $operation, $key = '', $expiry = 0) {
            global $_SGLOBAL, $_SCONFIG;

            $ckey_length = 4;	// 随机密钥长度 取值 0-32;
                    // 加入随机密钥，可以令密文无任何规律，即便是原文和密钥完全相同，加密结果也会每次不同，增大破解难度。
                    // 取值越大，密文变动规律越大，密文变化 = 16 的 $ckey_length 次方
                    // 当此值为 0 时，则不产生随机密钥

            $key = md5($key ? $key : $_SGLOBAL['authkey']);
            $keya = md5(substr($key, 0, 16));
            $keyb = md5(substr($key, 16, 16));
            $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';

            $cryptkey = $keya.md5($keya.$keyc);
            $key_length = strlen($cryptkey);

            $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
            $string_length = strlen($string);

            $result = '';
            $box = range(0, 255);

            $rndkey = array();
            for($i = 0; $i <= 255; $i++) {
                $rndkey[$i] = ord($cryptkey[$i % $key_length]);
            }

            for($j = $i = 0; $i < 256; $i++) {
                $j = ($j + $box[$i] + $rndkey[$i]) % 256;
                $tmp = $box[$i];
                $box[$i] = $box[$j];
                $box[$j] = $tmp;
            }

            for($a = $j = $i = 0; $i < $string_length; $i++) {
                $a = ($a + 1) % 256;
                $j = ($j + $box[$a]) % 256;
                $tmp = $box[$a];
                $box[$a] = $box[$j];
                $box[$j] = $tmp;
                $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
            }
            if($operation == 'DECODE') {
                if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
                    return substr($result, 26);
                } else {
                    return '';
                }
            } else {
                return $keyc.str_replace('=', '', base64_encode($result));
            }
        }

        //获取文件格式类型
        function extend($file_name) {
            $extend = pathinfo($file_name);
            $extend = strtolower($extend["extension"]);
            return $extend;
        }

        //获取文件内容
        function GetFileCon($file_name,$open_method) {
            $fp = fopen ($file_name,$open_method);
            $file_contents = file_get_contents($file_name);
            fclose ($fp);
            return $file_contents;
        }

        //生成文件夹
        function MakeFolder($filename){
            @mkdir($filename,0777);
        }

        //生成文件
        function MakeFile($config_filename,$contents) {
            $fp = fopen($config_filename,'w');
            fwrite($fp,$contents);
            fclose($fp);
        }

        //输出指定长度文本
        function CutTitle($str,$strlen,$other) {
            $j = 0;
            for($i=0;$i<$strlen;$i++)
            if(ord(substr($str,$i,1))>0xa0) $j++;
            if($j%2!=0) $strlen++;
            $rstr=substr($str,0,$strlen);
            if(strlen($str)>$strlen && $other){$rstr=$rstr."...";}
            echo $rstr;
        }


        //计算运行时间
        function RunTime($mod='') {
            static $first;
            static $prev;
            static $str;
            $time = explode(' ', microtime());
            $curr = $time[1] . substr($time[0],1,5);
            if(!$first) {
                $prev = $first = $curr+0;
            }else if($mod == 'end'){
                //$str .= '本次: '.intval(($curr - $prev) * 100000)/100000 . '<br/>';
                $str = '页面执行用时'.intval(($curr - $first) * 100000)/100000 . '秒';
                echo $str;
            }else{
                $str .= '本次: '.intval(($curr - $prev) * 100000)/100000 . '<br/>';
                $prev = $curr;
            }
        }

    //---------------------------------------------
    // 以下为兼容PHP5函数
    //---------------------------------------------

    if (!function_exists("file_get_contents")) {
        /**
         * 将整个文件读入一个字符串(兼容PHP3)
         *
         * @param string $f  文件名及路径
         * @return string 文件内容
         */
        function file_get_contents($f) {
            $h = @fopen ($f, "rb");
            if ($h) $c = @fread ($h, @filesize ($f));
            else return false;
            fclose ($h);
            return $c;
        }
    }

    if (!function_exists("file_put_contents")) {
        /**
         * 将一个字符串写入文件(兼容PHP3、PHP4)
         *
         * @param string $f  文件名及路径
         * @param string $d  需要写入的内容
         * @return mixed 写入文档失败则返回FALSE
         */
        function file_put_contents ($f,$d) {
            $fp = @fopen($f,"wb");
            if (!$fp) return false;
            fwrite($fp, $d);
            fclose($fp);
        }
    }

    if (!function_exists('http_build_query')){
        /**
         * 生成 url-encoded 之后的请求字符串
         *
         * @param array $a  关联（或下标）数组
         * @return string   Query URL 字符串
         */
        function http_build_query($a) {
            $f = '';$ret = '';
            foreach ($a as $i => $j) {
                if (!empty($j)) {
                    $ret .= "{$f}{$i}=".urlencode($j);
                    $f='&';
                }
            }
            return $ret;
        }       
     }
	 /**
         * 操作文件
         *
         * 记录后台管理员的操作动作。
         */
	function file_log($uname,$do){
		     $fp=fopen("log/log.txt",a);
			 $str=$uname."    ".$do."    ".date("Y-m-d H:i:s",time())."\r\n";
			 fwrite($fp,$str);
			 fclose($fp);
		}